package com.ruoyi.controller.system;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.vo.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.controller.BaseController;
import com.ruoyi.domain.SysDept;
import com.ruoyi.domain.SysRole;
import com.ruoyi.domain.SysUser;
import com.ruoyi.service.SysDeptService;
import com.ruoyi.service.SysPostService;
import com.ruoyi.service.SysRoleService;
import com.ruoyi.service.SysUserService;

@RequestMapping("system/user")
@RestController
public class SysUserController extends BaseController{
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysDeptService sysDeptService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysPostService sysPostService;
	
	/**
	 * 获取用户列表
	 * @param user
	 * @return
	 */
	@GetMapping("list")
	public TableDataInfo list(SysUser user) {
		logger.info("获取用户列表,user:{}",user);
		startPage();
		List<SysUser> list = sysUserService.selectUserList(user);
		return getDataTable(list);
	}
	
	/**
	 * 根据用户编号获取详细信息
	 * @param userId
	 * @return
	 */
	
	@GetMapping(value = {"/","/{userId}"})
	public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		logger.info("根据用户编号获取详细信息,userId:{}",userId);
		sysUserService.checkUserDataScope(userId);
		AjaxResult ajax = AjaxResult.success();
		List<SysRole> roles = sysRoleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", sysPostService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = sysUserService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", sysPostService.selectPostListByUserId(userId));
            List<Long> roleIds = sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
			/*
			 * List<Long> roleIds = new ArrayList<>(); 
			 * for(SysRole sysRole :sysUser.getRoles()) { 
			 * roleIds.add(sysRole.getRoleId()); 
			 * }
			 */
            ajax.put("roleIds", roleIds);        
        }
        return ajax;
	}
	

	
	/**
	 * 获取部门树列表
	 * @param dept
	 * @return
	 */
	@GetMapping("/deptTree")
	public AjaxResult deptTree(SysDept dept) {
		logger.info("获取部门树列表,dept:{}",dept);
		return AjaxResult.success(sysDeptService.selectDeptTreeList(dept));
	}
	
	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	@PostMapping
	public AjaxResult add(@Validated @RequestBody SysUser user) {
		logger.info("新增用户，user:{}",user);
		if (!sysUserService.checkUserNameUnique(user)) {
			return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
		} else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysUserService.checkPhoneUnique(user)) {
			return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
		} else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
			return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setCreateBy(getUsername());
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		return toAjax(sysUserService.insertUser(user));
	}
	
	/**
	 * 修改用户
	 * @param user
	 * @return
	 */
	@PutMapping
	public AjaxResult edit(@Validated @RequestBody SysUser user) {
		logger.info("修改用户，user:{}",user);
		sysUserService.checkUserAllowed(user);
		if (!sysUserService.checkUserNameUnique(user)) {
			return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
		} else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysUserService.checkPhoneUnique(user)) {
			return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		} else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
			return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setUpdateBy(getUsername());
		return toAjax(sysUserService.updateUser(user));
	}

	
}
